extends Control

@export var start_pos_y: float = 16
@export var middle_pos_y: float = 0
@export var end_pos_y: float = -16
@export var normal_show_duration: float = 1.5
@export var tween_duration: float = 0.2

@onready var h_box_container: HBoxContainer = $HBoxContainer

var item_config: ItemBaseConfig
@onready var icon_bg: TextureRect = $HBoxContainer/IconBg
@onready var icon_texture: TextureRect = $HBoxContainer/IconBg/IconTexture
@onready var label: Label = $HBoxContainer/Label


func init(config: ItemBaseConfig):
	item_config = config
	icon_texture.texture = ResourceManager.get_resource(item_config.icon_name)
	label.text = item_config.name


func start_anim():
	h_box_container.position.y = start_pos_y
	self.modulate.a = 0
	
	var tween = create_tween()
	tween.tween_property(h_box_container, "position:y", middle_pos_y, tween_duration) \
	.set_trans(Tween.TRANS_SINE) \
	.set_ease(Tween.EASE_OUT)
	
	var tween_alpha = create_tween()
	tween_alpha.tween_property(self, "modulate:a", 1.0, tween_duration) \
	.set_trans(Tween.TRANS_SINE) \
	.set_ease(Tween.EASE_OUT)
	
	await tween.finished
	modulate.a = 1
	h_box_container.position.y = middle_pos_y
	await get_tree().create_timer(normal_show_duration).timeout
	
	tween = create_tween()
	tween.tween_property(h_box_container, "position:y", end_pos_y, tween_duration) \
	.set_trans(Tween.TRANS_SINE) \
	.set_ease(Tween.EASE_IN)
	
	tween_alpha = create_tween()
	tween_alpha.tween_property(self, "modulate:a", 0.0, tween_duration) \
	.set_trans(Tween.TRANS_SINE) \
	.set_ease(Tween.EASE_OUT)
	
	await tween.finished
	queue_free()
	

func get_bound_rect() -> Rect2:
	var font = label.label_settings.font
	var font_size: int = label.label_settings.font_size
	var str_width: int = font.get_string_size(label.text, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x
	
	var h_box_sep: int = h_box_container.get_theme_constant("separation")
	
	var total_width = icon_bg.size.x + h_box_sep + str_width
	var total_height = icon_bg.size.y
	
	var pos = global_position
	
	return Rect2(pos, Vector2(total_width, total_height))
	

func is_disappearing():
	return h_box_container.position.y < middle_pos_y
	
